(function(window) {

var pccc = {
	$c:         null,
	$content:   null,
	$bottom:    null,
	connected:  false,
	pageID:     '',
	available:  true,
	timer:      null,
	videoIndex: 0
};

pccc.init = function() {
	pccc.$c       = $('#container');
	pccc.$content = pccc.$c.find('.content');
	pccc.$bottom  = pccc.$c.find('.footer');

	config.debug = (location.search.indexOf('debug') != -1);
	if(!config.debug) {
		$('body').attr('oncontextmenu', 'return false;');
		$('body').attr('onselectstart', 'return false;');
	}

	// -1.scale
	// var width  = window.innerWidth || document.documentElement.clientWidth;
	// var height = window.innerHeight || document.documentElement.clientHeight;
	// var scale  = pccc.scale = width/600;
	// pccc.$c.css('transform', 'scale('+scale+')');

	// 0.init socket
	pccc.so.init();

	// content 中按钮点击事件
	pccc.$content.on('click', '.icon-wrap:not(.disabled)', function() {
		var index = $(this).data('index');
		var url   = $(this).data('url');
		if(url) {
			so.emit('clickBtn', {index:'test-drive', type:'test-drive', pageID:pccc.pageID, url:url});

			// url 多语言
			url += '/' + (i18n.getLang()=='en' ? 'en' : 'zh');
			return window.location.href = url;
		}
		if (pccc.pageID=="movie") {
			pccc.videoIndex = $(this).index();
			so.emit('clickBtn', {index:index, type:'content-btn', pageID:pccc.pageID, move_name:$(this).find(".txt").eq(0).find("span").data("langkey")});
		}else{
			so.emit('clickBtn', {index:index, type:'content-btn', pageID:pccc.pageID});
		}
	});
	pccc.$bottom.on('click', '.icon-wrap', function() {
		var index = $(this).data('index');
		if (pccc.pageID=="movie") {
			so.emit('clickBtn', {index:index, type:'bottom-btn', pageID:pccc.pageID, move_name:$(this).find(".txt").eq(0).find("span").data("langkey")});
		}else{
			so.emit('clickBtn', {index:index, type:'bottom-btn', pageID:pccc.pageID});
		}
	});
};

/**
 * 当屏幕端页面变换
 * @param  {collect} data 屏幕端传递来的数据
 */
 // 操作传的值
var onPage = function(data) {

	console.log(data, 'data.id');

	$("#container").removeClass("start_page");
	$("body").removeClass("btd");
	console.warn('on page', data);
	/*---------- 页面效果 ----------*/
	if(data.pageID == 'play_video') {
		$('body').addClass('black');
	}else if(data.pageID == 'topic') {
		$('body').addClass('black');
	}else if (data.pageID == 'features'){
		// if (data.content.length==4) {
			if (data.bottom.length==1) {
				$('body').addClass('black');
			}else{
				$('body').removeClass('black');
			}
		// };
	}else
		$('body').removeClass('black');

	// if(data.pageID=='topic' || data.pageID=='wdy') {
		i18n.setLang(data.lang);
	// }

	console.warn(data);

	/*---------- content icons ----------*/
	var content = data.content;
	pccc.pageID = data.pageID;
	var iconTpls = {
		movie: function() {
			// return '<div class="small_size">%s%s%s<br/>%s%s%s</div>';
			return '<div class="video-wrap"><div class="video-list">%s%s%s%s%s%s</div><div class="movies_left_right"><div class="movies_left"></div><div class="movies_right"></div></div></div>'
		},
		1: '%s',
		2: '%s<br/>%s',
		3: '%s<br/>%s<br/>%s',
		4: '%s%s<br/>%s%s',
		5: '%s%s<br/>%s%s<br/>%s',
		6: '%s%s<br/>%s%s<br/>%s%s',
		7: '%s<br/>%s%s<br/>%s%s<br/>%s%s',
		8: '%s%s<br/>%s%s<br/>%s%s<br/>%s%s',
		10: '%s%s<br/>%s%s<br/>%s%s<br/>%s%s<br/>%s%s',
		27: '%s%s%s<br/>%s%s%s<br/>%s%s%s<br/>%s%s%s<br/>%s%s%s<br/>%s%s%s<br/>%s%s%s<br/>%s%s%s<br/>%s%s%s',
	};
	// if (data.pageID=="movie") {
	// 	iconTpls["6"]='<div class="small_size">%s%s%s<br/>%s%s%s</div>';
	// }
	if (data.pageID=="-show") {
		iconTpls["3"]='<div class="more_big_text">%s<br/>%s<br/>%s</div>';
	};
	if (data.pageID=="show") {
		iconTpls["3"]='<div class="more_big_text">%s<br/>%s<br/>%s</div>';
	};
	if (data.pageID=="play_video") {
		iconTpls["1"]='<div class="close_video_ui">%s</div>';
	};
	if (data.pageID=="features") {
			iconTpls["1"]='<div class="features_lr_list"></div><div class="features_under_list"><div class="features_under_img features_under_left"></div><div class="features_under_img features_under_right">%s</div></div>';
		if (data.content[0].img=="car_test_drive_white") {
			iconTpls["1"]='<div class="features_lr_list"></div><div class="features_under_list"><div class="features_under_img features_under_left">%s</div><div class="features_under_img features_under_right"></div></div>';
		}
		if (data.content[0].img!=="car_test_drive_white") {
		iconTpls["2"]='<div class="features_lr_list"></div><div class="features_under_list"><div class="features_under_img features_under_left">%s</div><div class="features_under_img features_under_right">%s</div></div>';
		}else{
		iconTpls["2"]='<div class="features_lr_list">%s</div><div class="features_under_list"><div class="features_under_img features_under_left">%s</div><div class="features_under_img features_under_right"></div></div>';
		}	
		iconTpls["3"]='<div class="features_lr_list">%s</div><div class="features_under_list"><div class="features_under_img features_under_left">%s</div><div class="features_under_img features_under_right">%s</div></div>';
	};
	if (data.pageID=="vehicleList") {
		iconTpls["6"]='<div class="list_car">%s%s<br/>%s%s<br/>%s%s</div>';
	}
	if (data.pageID=="vehicle_small_List") {
		if (data.content.length<7) {
			iconTpls["2"]='<div class="lists_car">%s</div><div class="under_list"><div class="under_img ">%s</div><div class="under_img"></div></div>';
			iconTpls["5"]='<div class="lists_car">%s<br/>%s<br/>%s</div><div class="under_list"><div class="under_img ">%s</div><div class="under_img">%s</div></div>';
			iconTpls["6"]='<div class="lists_car">%s%s<br/>%s%s<br/>%s%s</div><div class="under_list"><div class="under_img "></div><div class="under_img"></div></div>';
			iconTpls["4"]='<div class="lists_car">%s%s<br/>%s%s</div><div class="under_list"><div class="under_img "></div><div class="under_img"></div></div>';
			if (data.content[0].img.indexOf("panamera")==-1) {
				iconTpls["3"]='<div class="lists_car">%s<br/>%s<br/>%s</div><div class="under_list"><div class="under_img "></div><div class="under_img"></div></div>';
			}else{
				iconTpls["3"]='<div class="lists_car">%s<br/>%s</div><div class="under_list"><div class="under_img ">%s</div><div class="under_img"></div></div>';
			}
		}else{
			if(data.content.length==7){
				iconTpls["7"]='<div class="small_size lists_car">%s%s%s</br>%s%s%s</div><div class="under_list"><div class="under_img "></div><div class="under_img">%s</div></div>';
			}
			if(data.content.length==8){
				iconTpls["8"]='<div class="small_size lists_car">%s%s%s</br>%s%s%s</div><div class="under_list"><div class="under_img ">%s</div><div class="under_img">%s</div></div>';
			}
		}
	}
	var icons       = _.where(content, {type: 'icon'});
	var iconHtml    = '';
	if(icons.length > 0) {
		var iconTplList = iconTpls[data.pageID] || iconTpls[icons.length];
		iconTplList = [typeof iconTplList == 'function' ? iconTplList(): iconTplList];

		for(var i in icons) {
			if (icons[i].txt.lengt>15) {
				iconTplList.push(getIcon(icons[i].index, icons[i].img, icons[i].txt.replace("<br>","\n"), data.pageID, icons[i].url));
			}else{
				iconTplList.push(getIcon(icons[i].index, icons[i].img, icons[i].txt, data.pageID, icons[i].url));
			}
		}
		// if (data.pageID=="vehicle_small_List") {
		// 	iconHtml='<div class="lr_list"></div><div class="main_list"><div class="width_main main_cl"></div><div class="width_main main_cc"></div><div class="width_main main_cr"></div></div><div class="under_list"><div class="under_img under_left"></div><div class="under_img under_right"></div></div>';
		// }else if(data.pageID=="movie"){
		// 	iconHtml='<div class="movie_lr_list"></div><div class="movie_main_list"><div class="movie_width_main movie_main_cl"></div><div class="movie_width_main movie_main_cc"></div><div class="movie_width_main movie_main_cr"></div></div><div class="movie_under_list"><div class="movie_under_img movie_under_left"></div><div class="movie_under_img movie_under_right"></div></div>';
		// }else{
			iconHtml ='<div class="c_tittle"></div><div class="small_title font-21"></div>'+util.format.apply(util, iconTplList);
			if (data.content[0].title=="") {
				iconHtml =util.format.apply(util, iconTplList);
			};
		// }
	}
	//中间显示的img
		pccc.$content.html(iconHtml);
		if (data.content.length!==0) {
				if(data.content[0].title!==""){
					if (data.content[0].title.big_title=="Book_a_Drive") {
						$("body").addClass("btd");
					};
					if(data.content[0].title.type=="image"){
						$('.c_tittle').css("background-image","url(./image/car_title_"+data.content[0].title.big_title+".png)");
						$('.small_title').html(__(data.content[0].title.small_title));
					}else{
						if (data.content[0].title.big_title=="dealer") {
							$('.c_tittle').html(__("puxicenter_sh"));
						}else if(data.content[0].title.big_title=="snowforce"){
							$('.c_tittle').html(__("snowforce_Drive"));
						}else if(data.content[0].title.big_title=="principle"){
							$('.c_tittle').html(__("Principle_Drive"));
						}else if(data.content[0].title.big_title=="lemans"){
							$('.c_tittle').html(__("24hlemans"));
						}else if(data.pageID=="features"){
							$('.c_tittle').html(__(data.content[0].title.big_title));
							$('.small_title').html(__(data.content[0].title.small_title));
						}else{
							$('.c_tittle').html(__(data.content[0].title.big_title));
						}
					}
				}
		};
	/*---------- bottom icons ----------*/
	//底部img
	var bottom = data.bottom;
	var icons  = _.where(bottom, {type: 'icon'});
	var html   = '';
	for(var i in icons) {
		html += getIcon(icons[i].index, icons[i].img, icons[i].txt, data.pageID, icons[i].url);
	}
	pccc.$bottom.html(html);

	function liao_movie(action){
		$('.movies_left').css("display","block");
		$('.movies_right').css("display","block");
		if (action>4) {
			action=5
			$('.movies_right').css("display","none");
		};
		if (action<1) {
			action=0
			$('.movies_left').css("display","none");
		};
		pccc.scrollVideo(action);
	}
	if(data.pageID == "movie") {
		renderMovie();
		pccc.$content.find(".movies_right").click(function(){
				liao_movie(pccc.getVideoIndex()+1);
		});
		pccc.$content.find(".movies_left").click(function(){
				liao_movie(pccc.getVideoIndex()-1);
		});
	}
};

var renderMovie = function() {
	var $wrap   = pccc.$c.find('.video-list');
	var $items  = $wrap.children('.icon-wrap');
	var screenW = pccc.$c.width();
	var itemW   = $items.eq(0).width();

	var magin = (screenW - itemW*2) / 4;
	$items.css({
		'margin': '0 '+magin+'px',
		'width':  itemW
	});
	$wrap.css({
		'width':       (itemW + 2*magin) * ($items.length) + 1000,
		'margin-left': -itemW/2 - magin + screenW/2
	});

	var index = 0;
	pccc.getVideoIndex = function() {
		return index;
	};
	/**
	 * 滚动video list
	 * @param  {string} dir left || right
	 */
	pccc.scrollVideo = function(_index) {
		index = _index;
		if(pccc.$c.find('.video-list').length>0 && _index>=0 && _index<$items.length) {
			var pis = screenW/2;
			$items.removeClass('disabled');
			$wrap.transit({
				x: -screenW/2*index
			}, function() {
				$items.addClass('disabled').eq(index).removeClass('disabled');
			});
		}
	};
	pccc.scrollVideo(pccc.videoIndex || 0);
	pccc.videoIndex = 0;
	$wrap.css('opacity', 1);
};

var getIcon = function(index, img, txt, page, url) {
	if(page == 'topic') {
		img = ({
			'main_aboutporsche_icon': 'nav_aboutporsche',
			'main_pcpuxi_icon':       'nav_pcpuxi',
			'main_s_a_icon':          'nav_services',
			'main_motorsport_icon':   'nav_motorsport',
			'main_events_icon':       'nav_events'
		})[img] || img;
	}
	var tpl = '<div data-url="%s" data-index="%s" data-id="%s" class="icon-wrap"><div class="icon" style="background-image:url(./image/%s.png)"></div><div class="txt">%s</div></div>';
	if (page=="topic") {
		if ((img=="chinese_lang_w")||(img=="english_lang_w")) {
			var tpl = '<div style="position: absolute;right: 0px;margin-right: 10%;" data-url="%s" data-index="%s" data-id="%s" class="icon-wrap"><div class="icon" style="background-image:url(./image/%s.png)"></div><div class="txt">%s</div></div>';
		};
	};
	return util.format(tpl, url||'', index, img, img, txt);
};

var renderStatus = function() {
	if(!pccc.connected) {
		if (i18n.getLang()=="en") {
			pccc.$c.html('<h1>Disconnected OR Busy</h1>');
		}else{
			pccc.$c.html('<h1>断开连接或忙</h1>');
		}
	}
	var $status = pccc.$c.find('#status');
	$status.text(pccc.connected?'Connected':'NotConnected');
	if(pccc.connected)
		$status.addClass('connected');
	else
		$status.removeClass('connected');
};
var renderTips = function(tip) {
	pccc.$c.find('#tip').clearQueue().show().text(tip).fadeOut(5000);
};

var so = pccc.so = {
	socket: null
};
so.reconnect = function() {
	so.socket && so.socket.connect();
};
so.disconnect = function() {
	so.socket && so.socket.disconnect();
};
// 1
so.init = function() {
	so.socket = io.connect(config.socketUrl + '/iControl-socket');

	// 连接建立
	so.socket.on('control.connected', function(data) {
		console.warn('control.connected', data);
		pccc.connected = true;
		renderStatus();
	});

	// 受到讯息
	so.socket.on('tips', function(data) {
		renderTips(data);
	});

	// 连接断开
	so.socket.on('disconnect', function(data) {
		pccc.connected = false;
		renderStatus();
	});

	// 通信
	so.socket.on('screen.operate', function(data) {
		// 操作 data传的值
		console.warn('screen.operate', data);

		window.clearTimeout(pccc.timer);
		pccc.available = true;

		data = data || {};
		switch(data.action) {
			case 'onPage':
				onPage(data);
				break;
			case 'disconnect':
				pccc.so.disconnect();
				break;
		}
	});
};

/**
 * 传递数据到屏幕端
 * @param  {string} action 操作类型
 * @param  {collect} data   数据
 */
so.emit = function(action, data) {
	if(pccc.available) {
		window.clearTimeout(pccc.timer);
		pccc.timer = window.setTimeout(function() {
			pccc.available = true;
		}, 3000);
		pccc.available = false;

		data        = data || {};
		data.action = action || '';
		so.socket.emit('control.operate', data);
	}
};

$(pccc.init);
window.pccc = pccc;
})(window);